package com.wu.foodsafetyplayer.app.fragment.main;

import android.content.Intent;
import android.graphics.drawable.StateListDrawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.wu.foodsafetyplayer.R;
import com.wu.foodsafetyplayer.app.AddDeviceActivity;
import com.wu.foodsafetyplayer.app.AppVideoActivity;
import com.wu.foodsafetyplayer.app.LoginActivity;
import com.wu.foodsafetyplayer.app.adapter.MonitorVideoAdapter;
import com.wu.foodsafetyplayer.app.adapter.VideoNvaAdapter;
import com.wu.foodsafetyplayer.app.bean.DeviceByMomeBean;
import com.wu.foodsafetyplayer.app.bean.MonitorVideoBean;
import com.wu.foodsafetyplayer.app.dialog.DevicePopWindow;
import com.wu.foodsafetyplayer.app.fragment.BaseFragment;
import com.wu.foodsafetyplayer.http.CommonOkHttpClient;
import com.wu.foodsafetyplayer.utils.ACache;
import com.wu.foodsafetyplayer.utils.AnimationUtil;
import com.wu.foodsafetyplayer.utils.PopupUtil;
import com.wu.foodsafetyplayer.utils.SpUtil;
import com.wu.foodsafetyplayer.widget.MyGridView;

import java.io.IOException;

import androidx.annotation.NonNull;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class MonitorFragment extends BaseFragment implements View.OnClickListener, AdapterView.OnItemClickListener {
    private static final String TAG = MonitorFragment.class.getSimpleName();
    private GridView videoGridView;
    private MyGridView videoNvaGridView;
    private MonitorVideoBean monitorVideoBean;
    private DeviceByMomeBean deviceByMomeBean;
    private String res, resByMome;//设备数据

    private DevicePopWindow devicePopWindow;
    private ImageView f_nonitor_add;

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_monitor;
    }

    @Override
    protected void initView() {
        super.initView();
        f_nonitor_add = findViewById(R.id.f_nonitor_add);
        f_nonitor_add.setOnClickListener(this);

        devicePopWindow = new DevicePopWindow(getActivity());
        devicePopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                PopupUtil.INSTANCE.backgroundAlpha(getActivity(), 1f);
            }
        });

        //设备分类
        videoNvaGridView = findViewById(R.id.f_monitor_video_nva_gv);
        videoNvaGridView.setSelector(new StateListDrawable());//不要选中时的背景效果
        videoNvaGridView.setOnItemClickListener(this);
        VideoNvaAdapter videoNvaAdapter = new VideoNvaAdapter(getActivity());
        videoNvaGridView.setAdapter(videoNvaAdapter);
        //监控设备
        videoGridView = findViewById(R.id.f_monitor_video_gv);
        videoGridView.setOnItemClickListener(this);
        res = ACache.get(getActivity()).getAsString("live_data");
        resByMome = ACache.get(getActivity()).getAsString("live_data_by_mome");
        initPublicData();
    }

    /**
     * 初始化数据
     */
    public void initPublicData() {
        if (!TextUtils.isEmpty(res)) {
            try {
                monitorVideoBean = new Gson().fromJson("{\"data\": " + res + "}", MonitorVideoBean.class);
                if (monitorVideoBean != null && monitorVideoBean.data != null && !monitorVideoBean.data.isEmpty()) {
                    handler.sendEmptyMessage(PUBLIC_MSG);
                }
            } catch (JsonSyntaxException e) {
                e.printStackTrace();
            }
        }
        CommonOkHttpClient.FUNC_TASK.execute(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient().newBuilder()
                        .build();
                Request request = new Request.Builder()
                        .url("http://daxun.tpddns.cn:81/live/Query?username=admin&password=admin&treemode=0&name=")
                        .method("GET", null)
                        .addHeader("content-type", "form-data")
                        .addHeader("Cookie", "IDHTTPSESSIONID=r4EN2qalGkkbZUS")
                        .build();
                try {
                    Response response = client.newCall(request).execute();
                    String res2 = response.body().string();
                    Log.e(TAG, "-----initData: " + res2);
                    if (!TextUtils.isEmpty(res2)) {
                        if (res2.equals(res)) {
                            return;
                        }
                        ACache.get(getActivity()).put("live_data", res2);
                        monitorVideoBean = new Gson().fromJson("{\"data\": " + res2 + "}", MonitorVideoBean.class);
                        if (monitorVideoBean != null && monitorVideoBean.data != null && !monitorVideoBean.data.isEmpty()) {
                            handler.sendEmptyMessage(PUBLIC_MSG);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ClassCastException e) {
                    Log.e(TAG, "开始请求设备数据成功,解析失败");
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 初始化自己添加的设备的数据
     */
    public void initMyData() {
        if (!TextUtils.isEmpty(resByMome)) {
            deviceByMomeBean = new Gson().fromJson(resByMome, DeviceByMomeBean.class);
            if (deviceByMomeBean != null && deviceByMomeBean.items != null && !deviceByMomeBean.items.isEmpty()) {
                monitorVideoBean.data.clear();
                for (int i = 0; i < deviceByMomeBean.items.size(); i++) {
                    MonitorVideoBean.DataBean b = new MonitorVideoBean.DataBean();
                    b.name = deviceByMomeBean.items.get(i).name;
                    b.url = deviceByMomeBean.items.get(i).channels != null ? deviceByMomeBean.items.get(i).channels.get(0).url : "";
                    monitorVideoBean.data.add(b);
                }
                Log.e(TAG, "-----initData resByMome: 111更新UI");
                handler.sendEmptyMessage(PUBLIC_MSG);
            }
        }

        String paramUsername = ACache.get(getActivity()).getAsString("name");
        String paramPassword = ACache.get(getActivity()).getAsString("pass");
        String paramMemo = paramUsername + paramPassword;
        CommonOkHttpClient.FUNC_TASK.execute(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient().newBuilder()
                        .build();
                Request request = new Request.Builder()
                        .url("http://daxun.tpddns.cn:81/QueryOrgTreeByMemo?username=" + paramUsername + "&password=" + paramPassword + "&memo=" + paramMemo + "&hls=&rtsp=")
                        .method("GET", null)
                        .addHeader("content-type", "form-data")
                        .addHeader("Cookie", "IDHTTPSESSIONID=r4EN2qalGkkbZUS")
                        .build();
                try {
                    Response response = client.newCall(request).execute();
                    String res2 = response.body().string();
                    Log.e(TAG, "-----initData resByMome: " + res2);
                    if (!TextUtils.isEmpty(res2)) {
                        if (res2.equals(resByMome)) {
                            return;
                        }
                        ACache.get(getActivity()).put("live_data_by_mome", res2);
                        deviceByMomeBean = new Gson().fromJson(res2, DeviceByMomeBean.class);
                        if (deviceByMomeBean != null && deviceByMomeBean.items != null && !deviceByMomeBean.items.isEmpty()) {
                            monitorVideoBean.data.clear();
                            for (int i = 0; i < deviceByMomeBean.items.size(); i++) {
                                MonitorVideoBean.DataBean b = new MonitorVideoBean.DataBean();
                                b.name = deviceByMomeBean.items.get(i).name;
                                b.url = deviceByMomeBean.items.get(i).channels != null ? deviceByMomeBean.items.get(i).channels.get(0).url : "";
                                monitorVideoBean.data.add(b);
                            }
                            Log.e(TAG, "-----initData resByMome: 更新UI");
                            handler.sendEmptyMessage(PUBLIC_MSG);
                        } else {
                            handler.sendEmptyMessage(MY_MSG);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ClassCastException e) {
                    Log.e(TAG, "开始请求设备数据成功,解析失败");
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    final int PUBLIC_MSG = 0;
    final int MY_MSG = 1;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == PUBLIC_MSG) {
                MonitorVideoAdapter videoAdapter = new MonitorVideoAdapter(getActivity(), monitorVideoBean);
                videoGridView.setAdapter(videoAdapter);
            } else if (msg.what == MY_MSG) {
                Toast.makeText(getActivity(), "该账户下没发现在线设备", Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //添加摄像头
            case R.id.f_nonitor_add:
//                Toast.makeText(getActivity(), "当前版本无添加权限", Toast.LENGTH_SHORT).show();
                if (!SpUtil.INSTANCE.getUserInfo().getIsnoLogin()) {
                    devicePopWindow.showAsDropDown(f_nonitor_add, -150, 10);
                    PopupUtil.INSTANCE.backgroundAlpha(getActivity(), 0.8f);
                } else {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                }
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        switch (adapterView.getId()) {
            case R.id.f_monitor_video_nva_gv:
                videoNvaGridView.setCurrentPosition(i);
                AnimationUtil.setScaleAnimation(getActivity(), view);
                //共有设备
                if (i == 0) {
                    initPublicData();
                }
                //我的设备
                else if (i == 1) {
                    initMyData();
                } else {
                    Toast.makeText(getActivity(), "该分组暂无设备", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.f_monitor_video_gv:
                Intent intent = new Intent(getActivity(), AppVideoActivity.class);
                intent.putExtra("name", monitorVideoBean.data.get(i).name);
                intent.putExtra("url", monitorVideoBean.data.get(i).url);
                startActivity(intent);
                break;
        }
    }


}
